package com.zch.user.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.zch.user.dao.UserDao;

/**
 * dao层对象工具类
 * @author Administrator
 *
 */
public class XmlSession {
	private SqlSession session;
	public UserDao userMapper;
	/**
	 * 根据核心配置文件的相对路径获得sqlsession对象和Mapper的代理类
	 * @param resource
	 * @throws Exception
	 */
	public void getSession(String resource){
		try {
			//读取配置文件转换为输入流
			InputStream inputStream;
			inputStream = Resources.getResourceAsStream(resource);
			//获得工厂对象
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			//获得SqlSession对象
			session = sqlSessionFactory.openSession();
			//获得
			userMapper = session.getMapper(UserDao.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void closeSession(){
		//提交事务
		session.commit();
		if(session!=null){
			session.close();
		}
	}
}
